package com.hb.core.config.handler;

import cn.hutool.json.JSONUtil;
import com.hb.core.pojo.OrganizeInfo;
import com.hb.core.pojo.SectionOptions;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * describe:
 *   公告中标段的属性值映射
 * @author zhongdl
 * @date 2022/01/14
 */
@Slf4j
@MappedJdbcTypes(JdbcType.LONGVARCHAR)
@MappedTypes(SectionOptions.class)
public class SectionOptionsTypeHandler
        extends BaseTypeHandler<SectionOptions>
        implements HandlerConverter {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, SectionOptions sectionOptions, JdbcType jdbcType) throws SQLException {
        ps.setString(i, JSONUtil.parseObj(sectionOptions).toString());
    }

    @Override
    public SectionOptions getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String result = rs.getString(columnName);
        return convert(result);
    }

    @Override
    public SectionOptions getNullableResult(ResultSet rs, int columnName) throws SQLException {
        String result = rs.getString(columnName);
        return convert(result);
    }

    @Override
    public SectionOptions getNullableResult(CallableStatement cs, int columnName) throws SQLException {
        String result = cs.getString(columnName);
        return convert(result);
    }

    private SectionOptions convert(String result) {
        SectionOptions convert = convert(result, SectionOptions.class);
        if (convert == null) {
            log.warn("[{}] 无法转换成 com.hb.core.pojo.SectionOptions", result);
            return null;
        }
        return convert;
    }
}
